
CV.ContextMenu = new Class({

    Implements: Options,
    options: {
        actions: {},
        menu: 'contextmenu',
        offsets: {x:0, y:0},
        fadeSpeed: 200
    },
    initialize: function(tree, options) {
        this.tree = tree;
        tree.contextmenu = this;

        this.setOptions(options);
        this.menu = document.id(this.options.menu);

        this.fx = new Fx.Tween(this.menu, {
            property: 'opacity',
            duration:this.options.fadeSpeed
        });

        this.hide().start();
    },
    start: function() {

        this.menu.getElements('a').each(function(item) {
            item.addEvent('click', function(evt) {
                evt.stop();
                this.execute(item.get('id'));
                //this.fireEvent('click',[item, e]);
            }.bind(this));
        },this);

        document.id(document.body).addEvent('click', function(evt) {
            evt.stop();
            this.hide();
        }.bind(this));
    },
    show: function(evt) {
        this.fx.start(1);
        this.shown = true;
        return this;
    },
    hide: function() {
        if(this.shown) {
            this.fx.start(0);
            this.shown = false;

            this.menu.setStyles({
                'position':'absolute',
                'top':'-900000px',
                'display':'block'
            });
        }
        return this;
    },
    execute: function(action) {

        var node = this.tree.getSelected();
        switch(action) {
            case 'rename' :
                if(node) node.rename();
                break;
            case 'add':
                if(node) this.tree.add({ property: { name: 'new - rename' }}, node, 'inside');
                break;
            case 'show':
                this.tree.root.recursive(function() {
                    this.set({hidden: false});
                });
                break;
            case 'hide':
                if(node) node.set({hidden: true});
                break;
            case 'sort':
                break;
            case 'delete':
                if(confirm('delete?')) {
                    if(node) node.remove();
                }
                break;
        }
        this.hide();

        return this;
    }
});

